package TCPEcho;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TCPEchoSever3 {
    ServerSocket socket = null;
    public TCPEchoSever3(int port) throws IOException {
        socket = new ServerSocket(port);
    }

    public void start() throws IOException {
        ExecutorService service = Executors.newCachedThreadPool();
        System.out.println("服务器启动！！！");
        Socket clineSocket = socket.accept();
        service.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    processConnection(clineSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    private void processConnection(Socket clineSocket) throws IOException {
        System.out.printf("[%s:%d]，客户端上线！！！",clineSocket.getInetAddress(),clineSocket.getPort());
        try(InputStream inputStream = clineSocket.getInputStream();
            OutputStream outputStream = clineSocket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while(true){
                if(!scanner.hasNext()){
                    System.out.printf("[%s:%d]，客户端下线！！！",clineSocket.getInetAddress(),clineSocket.getPort());
                    break;
                }
                //读取请求
                String request = scanner.next();
                //根据请求构造响应
               String response = process(request);
                //将响应返回给客户端
                writer.println(response);
                writer.flush();
                //打印日志
                System.out.printf("[%s:%d],req:%s,resp:%s",clineSocket.getInetAddress(),clineSocket.getPort(),request,response);
            }
        }finally {
            clineSocket.close();
        }
    }

    private String process(String request) {
    return request;
    }

    public static void main(String[] args) throws IOException {
        TCPEchoSever3 tcpEchoSever3 = new TCPEchoSever3(4545);
        tcpEchoSever3.start();
    }
}
